#include <stdio.h>
#include "json.h"

int main(int argc, char *argv[]) {
    json_t diff;
    diff.load(argv[1]);
    FILE *f = fopen(argv[1], "w");
    print_json(diff);

    for (size_t i = 0;i < diff.size();i++) {
        fprintf(f, "diff --git a/%s b/%s\n", diff[i]["old_path"].string().c_str(), diff[i]["new_path"].string().c_str());
        if (diff[i]["a_mode"].string() != diff[i]["b_mode"].string()) {
            fprintf(f, "old mode %s\n", diff[i]["a_mode"].string().c_str());
            fprintf(f, "new mode %s\n", diff[i]["b_mode"].string().c_str());
        }
        fprintf(f, "--- a/%s\n", diff[i]["old_path"].string().c_str());
        fprintf(f, "+++ b/%s\n", diff[i]["new_path"].string().c_str());
        const char *p = diff[i]["diff"].string().c_str();
        bool first_line = true;
        for (size_t j = 0;j < diff[i]["diff"].string().size();j++) {
            char next = p[j + 1];
            if (p[j] == '\\')  {
                switch(next) {
                    case 'n': {
                        fprintf(f, "\n");
                        first_line = false;
                        break;
                    }
                    case 'r': fprintf(f, "\r");break;
                    case 't': fprintf(f, "\t");break;
                    case '\\': fprintf(f, "\\");break;
                    default: break;
                }
                j++;
            } else {
                if (first_line) {
                    if (p[j] == '-' || p[j] == '+') {
                        fprintf(f, " ");
                    } if (j != 0 && p[j] == '@' && next == '@') {
                        fprintf(f, " ");
                    }
                }
                fprintf(f, "%c", p[j]);
            }
        }
    }
    fprintf(f, "\\ No newline at end of file\n");
    fclose(f);
    return 0;
}